const isIos = window.plus?.os.name === 'iOS';

// 判断定位权限是否开启
const judgeIosPermissionLocation = () => {
  let result = false;
  const cllocationManger = window.plus.ios.import('CLLocationManager');
  const status = cllocationManger.authorizationStatus();
  result = status !== 2;
  console.log(`定位权限开启：${result}`);
  window.plus.ios.deleteObject(cllocationManger);
  return result;
};

// 判断麦克风权限是否开启
const judgeIosPermissionRecord = () => {
  let result = false;
  const avaudiosession = window.plus.ios.import('AVAudioSession');
  const avaudio = avaudiosession.sharedInstance();
  const permissionStatus = avaudio.recordPermission();

  console.log(`permissionStatus:${permissionStatus}`);
  if (permissionStatus === 1684369017 || permissionStatus === 1970168948) {
    console.log('麦克风权限没有开启');
  } else {
    result = true;
    console.log('麦克风权限已经开启');
  }
  window.plus.ios.deleteObject(avaudiosession);
  return result;
};

// 判断相机权限是否开启
const judgeIosPermissionCamera = () => {
  let result = false;
  const AVCaptureDevice = window.plus.ios.import('AVCaptureDevice');
  const authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
  console.log(`authStatus:${authStatus}`);

  if (authStatus === 3) {
    result = true;
    console.log('相机权限已经开启');
  } else {
    console.log('相机权限没有开启');
  }

  window.plus.ios.deleteObject(AVCaptureDevice);
  return result;
};

// 判断相册权限是否开启
const judgeIosPermissionPhotoLibrary = () => {
  let result = false;
  const PHPhotoLibrary = window.plus.ios.import('PHPhotoLibrary');
  const authStatus = PHPhotoLibrary.authorizationStatus();
  console.log(`authStatus:${authStatus}`);

  if (authStatus === 3) {
    result = true;
    console.log('相册权限已经开启');
  } else {
    console.log('相册权限没有开启');
  }

  window.plus.ios.deleteObject(PHPhotoLibrary);
  return result;
};

// Android权限查询
const requestAndroidPermission = permissionID => {
  return new Promise((resolve, reject) => {
    window.plus.android.requestPermissions(
      [permissionID],
      resultObj => {
        let result = 0;
        for (let i = 0; i < resultObj.granted.length; i++) {
          const grantedPermission = resultObj.granted[i];
          console.log(`已获取的权限：${grantedPermission}`);
          result = 1;
        }
        for (let i = 0; i < resultObj.deniedPresent.length; i++) {
          const deniedPresentPermission = resultObj.deniedPresent[i];
          console.log(`拒绝本次申请的权限：${deniedPresentPermission}`);
          result = 0;
        }
        for (let i = 0; i < resultObj.deniedAlways.length; i++) {
          const deniedAlwaysPermission = resultObj.deniedAlways[i];
          console.log(`永久拒绝申请的权限：${deniedAlwaysPermission}`);
          result = -1;
        }
        resolve(result);
      },
      error => {
        console.log(`申请权限错误：${error.code} = ${error.message}`);
        reject(
          new Error({
            code: error.code,
            message: error.message,
          }),
        );
      },
    );
  });
};

// 使用一个方法，根据参数判断权限
const judgeIosPermission = permissionID => {
  if (permissionID === 'location') {
    return judgeIosPermissionLocation();
  } else if (permissionID === 'camera') {
    return judgeIosPermissionCamera();
  } else if (permissionID === 'photoLibrary') {
    return judgeIosPermissionPhotoLibrary();
  } else if (permissionID === 'record') {
    return judgeIosPermissionRecord();
  }
  return false;
};

// 跳转到**应用**的权限页面
const gotoAppPermissionSetting = () => {
  if (isIos) {
    const UIApplication = window.plus.ios.import('UIApplication');
    const application2 = UIApplication.sharedApplication();
    const NSURL2 = window.plus.ios.import('NSURL');
    const setting2 = NSURL2.URLWithString('app-settings:');
    application2.openURL(setting2);

    window.plus.ios.deleteObject(setting2);
    window.plus.ios.deleteObject(NSURL2);
    window.plus.ios.deleteObject(application2);
  } else {
    const Intent = window.plus.android.importClass('android.content.Intent');
    const Settings = window.plus.android.importClass('android.provider.Settings');
    const Uri = window.plus.android.importClass('android.net.Uri');
    const mainActivity = window.plus.android.runtimeMainActivity();
    const intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    const uri = Uri.fromParts('package', mainActivity.getPackageName(), null);
    intent.setData(uri);
    mainActivity.startActivity(intent);
  }
};

// 检查系统的设备服务是否开启
const checkSystemEnableLocation = () => {
  if (isIos) {
    let result = false;
    const cllocationManger = window.plus.ios.import('CLLocationManager');
    result = cllocationManger.locationServicesEnabled();
    console.log(`系统定位开启:${result}`);
    window.plus.ios.deleteObject(cllocationManger);
    return result;
  } else {
    const context = window.plus.android.importClass('android.content.Context');
    const locationManager = window.plus.android.importClass('android.location.LocationManager');
    const main = window.plus.android.runtimeMainActivity();
    const mainSvr = main.getSystemService(context.LOCATION_SERVICE);
    const result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
    console.log(`系统定位开启:${result}`);
    return result;
  }
};

export {
  judgeIosPermission,
  requestAndroidPermission,
  checkSystemEnableLocation,
  gotoAppPermissionSetting,
};
